import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author： yu.Tan
 * @Date: 2020/8/20 10:04
 * @Description:
 */
public class ConsumerTopicB {

    private static final String QUEUE_NAME = "topic_queue_name1";
    private static final String EXCHANGE_NAME = "exchange_topic";
    //binding key
    private static final String EXCHANGE_ROUTE_KEY = "news.#";

    public static void main(String[] args) {

        //获取连接
        Connection connection = MQConnecitonUtils.getConnection();

        try {
            //创建消息通道
            final Channel channel = connection.createChannel();

            //创建队列
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            //绑定队列
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,EXCHANGE_ROUTE_KEY);

            channel.basicQos(1);

            //创建消费者对象
            DefaultConsumer consumer=new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String msg = new String(body, "UTF-8");
                    System.out.println("【ConsumerTopicA】receive message: " + msg);

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        channel.basicAck(envelope.getDeliveryTag(),false);
                    }
                }
            };

            channel.basicConsume(QUEUE_NAME,false,consumer);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}
